import { Repository, TreeRepository } from 'typeorm';
import { CategoryEntity } from './entities/shop-category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateCategoryDto, UpdateCategoryDto } from './dto/category.dto';
import { ResultData } from 'src/common/utils/result';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { threadId } from 'worker_threads';

export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly categopryRepo: TreeRepository<CategoryEntity>,
  ) {}

  async create(data: CreateCategoryDto) {
    const { parentId, ...rest } = data;
    let parent: CategoryEntity | null = null;
    if (parentId) {
      parent = await this.categopryRepo.findOne({ where: { id: data.parentId } });
    }

    await this.categopryRepo.save({
      ...rest,
      parent: parent,
    });
    return ResultData.ok();
  }
  async findTrees() {
    const trees = await this.categopryRepo.findTrees();
    return ResultData.ok(trees);
  }

  async findOne(id: number) {
    const category = await this.categopryRepo.findOne({ where: { id }, relations: ['parent'] });
    const { parent, ...rest } = category;
    return ResultData.ok({ ...rest, parentId: parent ? parent.id : null });
  }

  /** 获取某个分类的所有子分类 */
  async findDescendants(id: number) {
    const category = await this.categopryRepo.findOneBy({ id });
    return this.categopryRepo.findDescendantsTree(category);
  }

  async updateCategory(data: UpdateCategoryDto) {
    const { parentId, id, ...rest } = data;
    let parent: CategoryEntity | null = null;
    const category = await this.categopryRepo.findOne({ where: { id }, relations: ['parent'] });
    if (!category) {
      throw new NotFoundException('未找到本条分类');
    }
    if (parentId) {
      parent = await this.categopryRepo.findOne({ where: { id: parentId } });
    }
    category.parent = parent;

    this.categopryRepo.save({ ...category, ...rest });
    return ResultData.ok();
  }
  async remove(id: number) {
    const category = await this.categopryRepo.findOne({ where: { id }, relations: ['children'] });
    if (category.children && category.children.length > 0) {
      throw new BadRequestException('不能删除有子分类的数据');
    }
    await this.categopryRepo.remove(category);
    return ResultData.ok();
  }
}
